package com.hdax.service.Impl;

import com.hdax.entity.*;
import com.hdax.mappers.DepartmentMapper;
import com.hdax.mappers.EmployeeInfoMapper;
import com.hdax.service.ContractfileService;
import com.hdax.service.EmployeeInfoService;
import com.hdax.service.EmployeeService;
import com.hdax.service.RoleService;
import com.hdax.utils.PinYinUtil;
import com.hdax.utils.ResultUtil;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 员工信息服务impl
 *
 * @author Aizen
 * @date 2022/05/16
 */
@Service
public class EmployeeInfoServiceImpl implements EmployeeInfoService {

    @Autowired
    private HanyuPinyinOutputFormat hanyuPinyinOutputFormat;

    /**
     * 员工服务
     */
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工信息映射器
     */
    @Autowired
    private EmployeeInfoMapper employeeInfoMapper;

    /**
     * 部门映射器
     */
    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private RoleService roleService;


    @Override
    public List<Integer> countEmployeeInfo() {
        return null;
    }

    @Override
    public EmployeeInfo findEmployeeInfoById(Integer id) {
        EmployeeInfo employeeInfo = employeeInfoMapper.findEmployeeById(id);
        //根据部门ID拿到部门信息
        Department department = departmentMapper.findById(employeeInfo.getDepartmentId());
        employeeInfo.setDepartment(department);
        //判断是否是经理
        Role role = roleService.findById(employeeInfo.getRoleId());
        if(role.getDescription().indexOf("经理") != -1){
            employeeInfo.setJingLi(true);
        }else{
            employeeInfo.setJingLi(false);
        }

        return employeeInfo;
    }

    @Override
    public List<EmployeeInfo> findAll(int offset, int limit, EmployeeInfo employeeInfo) {
        return employeeInfoMapper.findAll(offset,limit,employeeInfo);
    }

    @Override
    public int getByNameCount(String empName) {
        return employeeInfoMapper.getByNameCount(empName);
    }

    @Override
    public int updateById(EmployeeInfo employeeInfo) {
        return employeeInfoMapper.updateById(employeeInfo);
    }


    /**
     * 合同服务
     */
    @Autowired
    private ContractfileService contractfileService;


    /**
     * 添加员工
     *
     * @param employeeInfo 员工信息
     * @return int
     */
    @Override
    public ResultUtil insert(EmployeeInfo employeeInfo) {
        Random random = new Random();
        //随机生成4位数字的字符串员工编号
        int empCode =  (random.nextInt(10000 - 1000) + 1000 + 1);
        //设置员工编号
        employeeInfo.setEmpCode(empCode+"");

        try {
            //添加员工档案
            employeeInfoMapper.insert(employeeInfo);

            //---------------------------------------------------------------------------------------------添加账号

            //如果添加档案无误，新增员工对应账号
            Employee employee = new Employee();
            //设置empId
            employee.setEmpId(employeeInfo.getId());
            //通过员工名称+手机号后4位===获取code
            String employeeInfoName = toPinyin(employeeInfo.getEmpName());
            String employeeInfoPhone = employeeInfo.getEmpPhone().substring(7, 11);
            String employeeCode = employeeInfoName+employeeInfoPhone;
            //设置code
            employee.setCode(employeeCode);
            //设置默认密码
            Md5Hash password = new Md5Hash("123", "qwerty", 1);
            employee.setPassword(password+"");
            employee.setRoleId(employeeInfo.getRoleId());
            employee.setDepartmentId(employeeInfo.getDepartmentId());
            if(employeeInfo.getEmpZhuanZhengDate()!=null&&!employeeInfo.getEmpZhuanZhengDate().equals("")){
                employee.setIsZhengShi(1);
            }else{
                employee.setIsZhengShi(2);
            }
            employee.setSalt("qwerty");
            employee.setOff(1);
            //添加账号
            employeeService.addEmployee(employee);

            //---------------------------------------------------------------------------------------------签署合同

            Contractfile contractfile = new Contractfile();
            //签署合同 时长
            double conTime = employeeInfo.getConTime();
            contractfile.setYear(conTime);
            //合同开始日期
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String startDate = sdf.format(date);
            contractfile.setStartDate(startDate);
            //合同结束日期
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            if(conTime>=1){
                calendar.add(Calendar.YEAR,(int)conTime);
            }else {
                calendar.add(Calendar.MONTH,(int)(conTime*10));
            }
            Date time = calendar.getTime();
            String endDate = sdf.format(time);
            contractfile.setEndDate(endDate);
            contractfile.setEmployeeInfoId(employeeInfo.getId());
            for (int i = 1; i <= 2; i++) {
                contractfile.setContractFileId(i);
                contractfileService.insertCon(contractfile);
            }
            return ResultUtil.upDataResult("添加成功！");
        } catch (Exception e) {
            return ResultUtil.upDataResult("添加失败了...");
        }
    }

    @Override
    public List<EmployeeInfo> selectAll() {
        return employeeInfoMapper.selectAll();
    }

    @Override
    public List<EmployeeInfo> findAllnotZhengShi() {
        return employeeInfoMapper.findAllNotZhengShi();
    }

    @Override
    public List<EmployeeInfo> emplist(int departmentId) {
        return employeeInfoMapper.emplist(departmentId);
    }

    @Override
    public int insertByView(EmployeeInfo employeeInfo) {
        return employeeInfoMapper.insertByView(employeeInfo);
    }

    @Override
    public List<EmployeeInfo> isnotnull() {
        return employeeInfoMapper.isnotnull();
    }

    @Override
    public List<EmployeeInfo> isnull() {
        return employeeInfoMapper.isnull();
    }

    @Override
    public List<EmployeeInfo> setDate(String empRuZhiDate) {
        return employeeInfoMapper.setDate(empRuZhiDate);
    }

    /**
     * updatepart
     *
     * @param employeeInfo 员工信息
     * @return {@link ResultUtil}
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class,propagation = Propagation.REQUIRED)
    public ResultUtil editEmployeeInfo(EmployeeInfo employeeInfo) {
        try {
            employeeInfoMapper.editEmployeeInfo(employeeInfo);
            //修改账号是否正式员工
            String empZhuanZhengDate = employeeInfo.getEmpZhuanZhengDate();
            if(empZhuanZhengDate!=null&&!empZhuanZhengDate.equals("")){
                Employee employee = new Employee();
                employee.setEmpId(employeeInfo.getId());
                employee.setIsZhengShi(1);
                employeeService.updateById(employee);
            }

            //同时修改账号里的部门和角色
            Employee employee = new Employee();
            employee.setEmpId(employeeInfo.getId());
            employee.setDepartmentId(employeeInfo.getDepartmentId());
            employee.setRoleId(employeeInfo.getRoleId());
            employeeService.updateByInfo(employee);


        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.upDataResult("修改失败了...");
        }
        return ResultUtil.upDataResult("修改成功！");
    }

    @Override
    public List<EmployeeInfo> getAllEmployeeInfo() {
        List<EmployeeInfo> employeeInfoList = employeeInfoMapper.getAllInfo();
        List<EmployeeInfo> resultEmployeInfoList = new ArrayList<>();
        employeeInfoList.forEach(employeeInfo -> {
            Integer roleId = employeeInfo.getRole().getId();
            //该员工的角色
            Role role = roleService.findById(roleId);
            if (role.getDescription().indexOf("经理")==-1){
                resultEmployeInfoList.add(employeeInfo);
            }
        });
        return resultEmployeInfoList;
    }

    @Override
    public EmployeeInfo getEmployeeInfoById(Integer id) {
        return employeeInfoMapper.findEmployeeById(id);
    }

    @Override
    public List<EmployeeInfo> findEmployeeInfoByDepartmentId(int id) {
        return employeeInfoMapper.findEmployeeInfoByDepartmentId(id);
    }

    @Override
    public List<EmployeeInfo> findEmployeeInfoByNotZhengShi(int id) {
        return employeeInfoMapper.findEmployeeInfoByNotZhengShi();
    }

    @Override
    public List<EmployeeInfo> getShowEmployeeInfoList(EmployeeInfo employeeInfo) {
        List<EmployeeInfo> employeeInfoList = new ArrayList<>();
        //不是管理员就查询当前部门下的员工
        if(employeeInfo.getId()!=1){
            employeeInfoList = findEmployeeInfoByDepartmentId(employeeInfo.getDepartment().getId());
        }else {
            //是管理员就查询所有非正式员工
            employeeInfoList = findEmployeeInfoByNotZhengShi(employeeInfo.getId());
        }
        return employeeInfoList;
    }

    @Override
    public Integer findCount() {
        return employeeInfoMapper.findCount();
    }


    public String toPinyin(String chinese){
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();
        hanyuPinyinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        hanyuPinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], hanyuPinyinOutputFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else{
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }



}
